package com.yx.frame.builder.code;


import java.util.List;

import com.yx.frame.builder.validate.Validator;
import com.yx.frame.builder.xml.MethodParmXml;
import com.yx.frame.builder.xml.MethodXml;
import com.yx.frame.builder.xml.UpdateMethodContentXml;
import com.yx.frame.builder.xml.UpdateMethodContentXml.UpdateSql;
public class UpdateMethodBuilder extends MethodBuilder {

	public UpdateMethodBuilder(String className,String shortClassName,MethodXml method) throws Exception {
		super(className,shortClassName,method);
	}

	public StringBuffer getJavaCode() throws Exception {
		String javaParmsStr = "";
		String daoParmSre="";
		UpdateMethodContentXml updateMethodContentXml=(UpdateMethodContentXml)getMethod().getMethodContentXml();		
		List<MethodParmXml> methodParms=getMethod().getMethodParms();
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml = methodParms.get(i);			
			String parmType = "String";
			if (methodParmXml.isMutilistType()) {
				parmType = "JSONArray";
			}
			javaParmsStr = javaParmsStr + parmType + " "+ methodParmXml.getName() + ",";
			daoParmSre=daoParmSre+methodParmXml.getName()+",";				
		}
		String userDefineDatasource= updateMethodContentXml.getUserDefineDatasource();
		if("true".equals(userDefineDatasource)){
			javaParmsStr=javaParmsStr+"String DatasourceOf"+ this.getMethod().getName()+ ",";
			daoParmSre=daoParmSre+"DatasourceOf"+ this.getMethod().getName()+ ",";
		}
		if (javaParmsStr.endsWith(","))
			javaParmsStr = javaParmsStr.substring(0, javaParmsStr.length() - 1);
		if(daoParmSre.endsWith(",")){
			daoParmSre = daoParmSre.substring(0, daoParmSre.length() - 1);
		}
		

		StringBuffer code = new StringBuffer();
		code.append("\r\n");
		code.append("	/////////////////////////////////////////////////////////////////////\r\n");
		code.append("	//编号：" + this.getMethod().getId()+ "\r\n");
		code.append("	//说明：" + this.getMethod().getComment()+ "\r\n");
		code.append("	//作者：" + this.getMethod().getAuthor() + "\r\n");
		code.append("	//日期：" + this.getMethod().getDate() + "\r\n");
		code.append("	/////////////////////////////////////////////////////////////////////\r\n");
		code.append("\r\n");
		
		code.append("	//外部调用方法，用于客户端远程调用服务\r\n");
		code.append("	public static ServiceResult "+ this.getMethod().getName()+"(User user, JSONObject obj)throws Exception {\r\n");
		//code.append("		String databaseName=\""+this.getMethod().getDatabaseName()+"\";\r\n");
		//code.append("		"+getClassName()+" daoControl=new "+getClassName()+"(databaseName);\r\n");
		
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml = methodParms.get(i);
			if(methodParmXml.isMutilistType()){
				code.append("		JSONArray "+ methodParmXml.getName()+"=obj.getJSONArray(\""+methodParmXml.getName()+"\");\r\n");
			}else{
				code.append("		String "+ methodParmXml.getName()+"=obj.getString(\""+methodParmXml.getName()+"\");\r\n");
			}
			Validator[] validators = methodParmXml.getValidators();
			if(methodParmXml.isMutilistType()){
				if(validators.length>0){
					code.append("		if("+methodParmXml.getName()+"==null)return new ServiceError(\""+ methodParmXml.getComment() +"不能为空\");\r\n");
					code.append("		for(int i=0,n="+methodParmXml.getName()+".length();i<n;i++){\r\n");
					for (int vIdx = 0; vIdx < validators.length; vIdx++) {
						Validator validator = validators[vIdx];
						code.append("			if(!" + validator.getStaticMethodName() + "("+ methodParmXml.getName() + ".getString(i))) return new ServiceError(\""+ methodParmXml.getComment() +"要求填写"
								+ validator.getComment() + "\");\r\n");
					}
					code.append("		}\r\n");
				}
			}else{
				for (int vIdx = 0; vIdx < validators.length; vIdx++) {
					Validator validator = validators[vIdx];
					code.append("		if(!" + validator.getStaticMethodName() + "("+ methodParmXml.getName() + ")) return new ServiceError(\""+ methodParmXml.getComment() + "要求填写"	+ validator.getComment() + "\");\r\n");
				}
			}
		}
		
		if("true".equals(userDefineDatasource)){
			code.append("		String DatasourceOf"+ this.getMethod().getName()+"=obj.getString(\"DatasourceOf"+this.getMethod().getName()+"\");\r\n");
		}
		code.append("		List<int[]> resultSet= "+getClassName()+"."+this.getMethod().getName()+"Dao("+daoParmSre+");\r\n");
		code.append("		ServiceResult serviceResultReturnObj=Format.convertServiceResult(resultSet);\r\n");		
		code.append("		serviceResultReturnObj.setServiceMessage(\"执行成功\");\r\n");
		String callback= ((UpdateMethodContentXml) getMethod().getMethodContentXml()).getCallback();
		if(null!=callback&&!"".equals(callback)){
			code.append("		serviceResultReturnObj="+callback+"(user,serviceResultReturnObj);\r\n");
		}
		if("true".equals(this.getMethod().getRemoveMemcachedUserLicense())){
			code.append("		user.removeMemStoragedUser();\r\n");
		}
		code.append("		return serviceResultReturnObj;\r\n");
		code.append("	}\r\n");
		
		code.append("	//内部数据库处理\r\n");
		code.append("	public static List<int[]> " + this.getMethod().getName() + "Dao("+ javaParmsStr + ")  throws Exception {\r\n");
		code.append("		List<SqlEntry> sqls = new ArrayList<SqlEntry>();\r\n");
		code.append("		SqlEntry sqlEntry=null;\r\n");	
		code.append("		String[] parmsTypeArray=null;\r\n");
		code.append("		String[] parmsValueArray=null;\r\n");
		List<UpdateSql> transaction= updateMethodContentXml.getTransaction();
		for (int sqlIdx = 0; sqlIdx < transaction.size(); sqlIdx++) {
			UpdateSql sqlDiscription = transaction.get(sqlIdx);
			code.append("		sqlEntry=new SqlEntry(\""+sqlDiscription.getSql()+"\");\r\n");	
			if(sqlDiscription.isLoop()){				
				String loopby=sqlDiscription.getLoopby();	
				code.append("		for(int i=0,n="+loopby+".length();i<n;i++){\r\n");
				String parmsTypeArray="parmsTypeArray=new String[]{";
				String parmsValueArray="parmsValueArray=new String[]{";
				for (int i = 0; i < methodParms.size(); i++) {
					MethodParmXml methodParmXml = methodParms.get(i);
					if((sqlIdx+1)==Integer.parseInt(methodParmXml.getSqlIndex())){
						parmsTypeArray=parmsTypeArray+"\""+methodParmXml.getType()+"\",";					
						parmsValueArray=parmsValueArray+methodParmXml.getName()+ ".getString(i),";
					}			
				}
				if (parmsTypeArray.endsWith(",")){
					parmsTypeArray = parmsTypeArray.substring(0, parmsTypeArray.length() - 1);
					parmsValueArray = parmsValueArray.substring(0, parmsValueArray.length() - 1);
				}
				parmsTypeArray=parmsTypeArray+"};";
				parmsValueArray=parmsValueArray+"};";
				code.append("			if(i==0){\r\n");
				code.append("				"+parmsTypeArray+"\r\n");
				code.append("				sqlEntry.setParamType(parmsTypeArray);\r\n");
				code.append("			}\r\n");
				code.append("			"+parmsValueArray+"\r\n");
				code.append("			sqlEntry.addParms(parmsValueArray);\r\n");
				code.append("		}\r\n");
			}else{
				String loopby=sqlDiscription.getLoopby();			
				String parmsTypeArray="parmsTypeArray=new String[]{";
				String parmsValueArray="parmsValueArray=new String[]{";
				for (int i = 0; i < methodParms.size(); i++) {
					MethodParmXml methodParmXml = methodParms.get(i);
					if((sqlIdx+1)==Integer.parseInt(methodParmXml.getSqlIndex())){
						parmsTypeArray=parmsTypeArray+"\""+methodParmXml.getType()+"\",";					
						parmsValueArray=parmsValueArray+methodParmXml.getName()+ ",";
					}			
				}
				if (parmsTypeArray.endsWith(",")){
					parmsTypeArray = parmsTypeArray.substring(0, parmsTypeArray.length() - 1);
					parmsValueArray = parmsValueArray.substring(0, parmsValueArray.length() - 1);
				}
				parmsTypeArray=parmsTypeArray+"};";
				parmsValueArray=parmsValueArray+"};";
				code.append("		"+parmsTypeArray+"\r\n");
				code.append("		sqlEntry.setParamType(parmsTypeArray);\r\n");
				code.append("		"+parmsValueArray+"\r\n");
				code.append("		sqlEntry.addParms(parmsValueArray);\r\n");
			}
			code.append("		sqls.add(sqlEntry);\r\n");
		}
		if("true".equals(userDefineDatasource)){
			code.append("		String databaseName=DatasourceOf"+ this.getMethod().getName()+";\r\n");
		}else{
			code.append("		String databaseName=\""	+ updateMethodContentXml.getDatasource() + "\";\r\n");
		}
		code.append("		Sql sqlControl=new Sql(databaseName);\r\n");
		code.append("		return sqlControl.update(sqls);\r\n");
		code.append("	}\r\n");
		code.append("\r\n");
		return code;
	}
	
	public StringBuffer[] getJsWebCode(String jsControlName) throws Exception{
		StringBuffer code = new StringBuffer();
		
		String jsParmsStr = "";
		String jsonParm="";
		String parmInputDiscription="";
		List<MethodParmXml> methodParms=getMethod().getMethodParms();
		for (int i = 0; i < methodParms.size(); i++) {
			MethodParmXml methodParmXml  = methodParms.get(i);
			jsParmsStr = jsParmsStr + methodParmXml.getName()+ ",";
			if(methodParmXml.isMutilistType()){
				jsonParm = jsonParm + methodParmXml.getName()+":"+methodParmXml.getName()+ ",";
			}else{
				jsonParm = jsonParm + methodParmXml.getName()+":"+methodParmXml.getName()+ ",";
			}
			if(methodParmXml.isMutilistType()){
				parmInputDiscription=parmInputDiscription+(i+1)+"、"+methodParmXml.getName()+"："+methodParmXml.getComment()+"&nbsp;-"+methodParmXml.getType()+"数组（"+methodParmXml.getValidator()+"）<br>";
			}else{
				parmInputDiscription=parmInputDiscription+(i+1)+"、"+methodParmXml.getName()+"："+methodParmXml.getComment()+"&nbsp;-"+methodParmXml.getType()+"（"+methodParmXml.getValidator()+"）<br>";
			}
		}
		UpdateMethodContentXml updateMethodContentXml=(UpdateMethodContentXml)getMethod().getMethodContentXml();	
		String userDefineDatasource= updateMethodContentXml.getUserDefineDatasource();
		if("true".equals(userDefineDatasource)){
			jsParmsStr = jsParmsStr+"DatasourceOf"+ this.getMethod().getName()+",";
			jsonParm = jsonParm +"DatasourceOf"+ this.getMethod().getName()+":"+"DatasourceOf"+ this.getMethod().getName()+ ",";
		}
		String sampleParmStr=jsParmsStr;
		sampleParmStr=splitParmsHtml(sampleParmStr);
		jsParmsStr = jsParmsStr + "callbackFunction,";
		if (jsParmsStr.endsWith(","))
			jsParmsStr = jsParmsStr.substring(0, jsParmsStr.length() - 1);
		if (jsonParm.endsWith(","))
			jsonParm = jsonParm.substring(0, jsonParm.length() - 1);
		jsonParm="{"+jsonParm+"}";
		
		//code.append("\r\n");
		StringBuffer returnResulsString=new StringBuffer();
		returnResulsString.append("返回值：updateResult为整形数组的数组，每个数组元素为数据库更新的返回值\r\n");
		StringBuffer sampleString=new StringBuffer();
		sampleString.append("	"+jsControlName+"." +this.getMethod().getName()+"_"+this.getMethod().getId()+ "("+sampleParmStr+"function(isOK,message,updateResult){   <br>\r\n");
		sampleString.append("	     &nbsp;&nbsp;if(isOK){//服务调用成功,从数组updateResult中取出返回数据<br>\r\n");
		sampleString.append("	     &nbsp;&nbsp;}else{//服务调用失败，返回错误信息<br>\r\n");
		sampleString.append("	         &nbsp;&nbsp; &nbsp;&nbsp;var errorMessage=message;<br>\r\n");
		sampleString.append("	     &nbsp;&nbsp;}<br>\r\n");
		sampleString.append("	});\r\n");
		
		StringBuffer html=JsFileWriter.htmlStr(this.getMethod().getIsMobilApp(),""+this.getMethod().getId(),
				this.getMethod().getName()+"_"+this.getMethod().getId() + "("	+ splitParmsHtml(jsParmsStr) + ")", this.getMethod().getComment(), this.getMethod().getAuthor(), this.getMethod().getDate(), parmInputDiscription, returnResulsString.toString(), sampleString.toString());
		
		//code.append("\r\n");
		code.append("	this."+this.getMethod().getName()+"_"+this.getMethod().getId()+ "=function(" + jsParmsStr + "){");
		code.append("var data = "+jsonParm+";");
		code.append("this.jsonPost("+this.getMethod().getId()+","+this.getMethod().getAsyncService()+",data,function(jsonData,callback){callback(jsonData.IsOK, jsonData.Message,jsonData.Result);},callbackFunction);");		
		code.append("};\r\n");
		return new StringBuffer[]{code,html};
	}
}
